/*
 * Created on 2004-5-21 To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */

package cn.com.yinhex.as.util;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author test To change the template for this generated type comment go to
 *         Window - Preferences - Java - Code Generation - Code and Comments
 */
public class ParamUtil {

	HashMap pu_map = null;

	public static boolean chchars = true;

	private HttpServletRequest req = null;

	public HttpServletRequest getRequest() {
		return req;
	}

	/**
	 * 构造函数
	 * 
	 * @param request
	 * @param requestmode
	 *            区分get和post
	 */
	public ParamUtil(HttpServletRequest request, String requestmode) {
		req = request;
		pu_map = new HashMap();
		/*
		 * if (StringUtil.isFine(request.getQueryString())) { querystring =
		 * request.getQueryString().toString().replace('?', '&'); }
		 */
	}

	/**
	 * 默认得到不区分
	 * 
	 * @param request
	 */
	public ParamUtil(HttpServletRequest request) {
		req = request;
		pu_map = new HashMap();
	}

	/**
	 * 得到传递参数的数字形式,如果没有这个参数,则返回normal
	 * 
	 * @param paramname
	 * @param normal
	 * @return
	 */
	public int getInt(String paramname, int normal) {
		try {
			return Integer.parseInt(get_post(paramname));
		} catch (Exception e) {
			return normal;
		}
	}

	public int getInt(String paramname) {
		try {
			return Integer.parseInt(get_post(paramname));
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 得到传递参数的字符串形式,如果没有这个参数,返回normal
	 * 
	 * @param paramname
	 * @param normal
	 * @return
	 */
	public String getString(String paramname, String normal) {
		try {
			return get_post(paramname);
		} catch (Exception e) {
			return normal;
		}
	}

	public String getString(String paramname) {
		try {
			return get_post(paramname);
		} catch (Exception e) {
			return "";
		}
	}

	public String getSourceString(String paramname) {
		try {
			return get_post(paramname, false);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 得到传递参数的长整型形式，如果没有这个参数，返回normal
	 * 
	 * @param paramname
	 * @return
	 */
	public long getLong(String paramname, long normal) {
		try {
			return Long.parseLong(get_post(paramname));
		} catch (Exception e) {
			return normal;
		}
	}

	public long getLong(String paramname) {
		try {
			return Long.parseLong(get_post(paramname));
		} catch (Exception e) {
			return (long) 0;
		}
	}

	/**
	 * 得到传递参数的双精度数形式，如果没有这个参数，返回normal
	 * 
	 * @param paramname
	 * @param normal
	 * @return
	 */
	public double getDouble(String paramname, double normal) {
		try {
			return Double.parseDouble(get_post(paramname));
		} catch (Exception e) {
			return normal;
		}
	}

	public double getDouble(String paramname) {
		try {
			return Double.parseDouble(get_post(paramname));
		} catch (Exception e) {
			return (double) 0;
		}
	}

	/**
	 * 得到传递参数的浮点数形式，如果没有这个参数，返回normal
	 * 
	 * @param paramname
	 * @param normal
	 * @return
	 */
	public float getFloat(String paramname, float normal) {
		try {
			return Float.parseFloat(get_post(paramname));
		} catch (Exception e) {
			return normal;
		}
	}

	public float getFloat(String paramname) {
		try {
			return Float.parseFloat(get_post(paramname));
		} catch (Exception e) {
			return (float) 0;
		}
	}

	public boolean getBoolean(String paramname) {
		try {
			String param = get_post(paramname).toLowerCase();
			if (param.indexOf("y") > -1 || param.indexOf("on") > -1 || param.indexOf("true") > -1 || param.indexOf("1") > -1
					|| param.indexOf("yes") > -1) {
				return true;
			}
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	public int getBooleanInt(String paramname) {
		try {
			String param = get_post(paramname).toLowerCase();
			if (param.indexOf("y") > -1 || param.indexOf("on") > -1 || param.indexOf("true") > -1 || param.indexOf("1") > -1
					|| param.indexOf("yes") > -1) {
				return 1;
			}
			return 0;
		} catch (Exception e) {
			return 0;
		}
	}

	public boolean isPost() {
		if (req.getMethod().indexOf("P") > -1) {
			return true;
		}
		return false;
	}

	/**
	 * 区分get和post
	 * 
	 * @param paramname
	 * @return @throws Exception
	 */
	private String get_post(String paramname) throws Exception {
		return get_post(paramname, true);
	}

	private String get_post(String paramname, boolean chchars) throws Exception {
		/**
		 * if (req.getParameter(paramname) != null) { int findparam =
		 * querystring.indexOf("&" + paramname + "="); if (mode.equals("get")) {
		 * if (findparam > 0) { return req.getParameter(paramname); } } else if
		 * (mode.equals("post")) { if (findparam == 0) { return
		 * req.getParameter(paramname); } } }
		 */
		String s = (String) pu_map.get(paramname);
		if (s == null) {
			s = req.getParameter(paramname);
		}
		if (s == null) {
			throw new IllegalArgumentException();
		}
		if (chchars) {
			s = StringUtil.htmlSpecialChars(s);
		} else {
			s = s.replaceAll("\'", "&#039;");
		}
		while (s.indexOf("%") == 0
				&& (s.lastIndexOf("%") == s.length() - 3 || s.lastIndexOf("%") == s.length() - 5 || s.lastIndexOf("%") == s.length() - 7 || s
						.lastIndexOf("%") == s.length() - 9)) {
			s = URLDecoder.decode(s, req.getCharacterEncoding());
		}
		return s.trim();
	}

	public void put(String key, String value) {
		pu_map.put(key, value);
	}

	public String[] getStrings(String paramname) {
		return req.getParameterValues(paramname);
	}

	public String ip() {
		return req.getRemoteAddr();
	}

	public String referer() {
		return req.getHeader("referer");
	}

	public String[] getNames() {
		Enumeration enume = req.getParameterNames();
		Iterator mi = pu_map.keySet().iterator();
		ArrayList list = new ArrayList();
		while (enume.hasMoreElements()) {
			list.add(enume.nextElement());
		}
		while (mi.hasNext()) {
			list.add(mi.next());
		}
		String[] names = new String[list.size()];
		for (int i = 0; i < names.length; i++) {
			names[i] = (String) list.get(i);
		}
		return names;
	}

	public void sendCookie(String prefix, HttpServletResponse res) {
		Enumeration enu = req.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			String[] values = req.getParameterValues(name);
			String value = "";
			for (int i = 0; values != null && i < values.length; i++) {
				value += values[i];
				if (i != values.length - 1) {
					value += "_,_@_";
				}
			}
			Cookie c = new Cookie("param_" + prefix + "_" + name, StringUtil.fcEncode(value));
			res.addCookie(c);
		}
	}

	public void removeCookie(String prefix, HttpServletResponse res) {
		Cookie[] cookies = req.getCookies();
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			String name = cookies[i].getName();
			if (name.startsWith("param_" + prefix + "_")) {
				cookies[i].setMaxAge(0);
				res.addCookie(cookies[i]);
			}
		}
	}

	public DOC getCookieParam(String prefix) {
		Cookie[] cookies = req.getCookies();
		DOC doc = new DOC();
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			String name = cookies[i].getName();
			if (name != null && name.startsWith("param_" + prefix + "_")) {
				doc.put(name.replaceAll("param_" + prefix + "_", ""), StringUtil.fcDecode(cookies[i].getValue()));
			}
		}
		return doc;
	}

	public final String getIP() {
		if (req == null) {
			return "";
		}
		String ip = req.getHeader("RealIP");
		if (!StringUtil.isFine(ip)) {
			ip = req.getHeader("RealIP2");
		}
		if (!StringUtil.isFine(ip)) {
			ip = req.getHeader("X-Forwarded-For");
		}
		if (!StringUtil.isFine(ip)) {
			ip = req.getRemoteAddr();
			if (ip == null) {
				ip = "";
			}
		}
		return ip.substring(ip.lastIndexOf(",") + 1).trim();
	}
}
